package org.hxzon.tapestry5.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.services.Response;

public class FileStreamResponse implements StreamResponse {

    protected final String contentType;

    protected final InputStream stream;

    protected final String filename;

    private final boolean inline;

    private static final String defaultContentType = "application/x-download";//"application/octet-stream"

    public FileStreamResponse(InputStream stream, String filename) {
        this(stream, filename, defaultContentType, false);
    }

    public FileStreamResponse(InputStream stream, String filename, boolean inline) {
        this(stream, filename, defaultContentType, inline);
    }

    public FileStreamResponse(InputStream stream, String filename, String contentType) {
        this(stream, filename, contentType, false);
    }

    public FileStreamResponse(InputStream stream, String filename, String contentType, boolean inline) {
        this.filename = filename;
        this.contentType = contentType;
        this.stream = stream;
        this.inline = inline;
    }

    public String getContentType() {
        return contentType;
    }

    public InputStream getStream() throws IOException {
        return stream;
    }

    public void prepareResponse(Response response) {
        String urlFilename = null;
        try {
//			urlFilename=java.net.URLEncoder.encode(filename, "UTF-8");
            urlFilename = new String(filename.getBytes(), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
        }
        if (urlFilename == null) {
            urlFilename = filename;
        }
        if (inline) {
            response.setHeader("Content-Disposition", "inline;");
        } else {
            response.setHeader("Content-Disposition", "attachment;filename=\"" + urlFilename + "\"");
        }
    }

}
